import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { LayerDataSet, BaseLayerViewModel, UnifiedMapService, ImageryTileLayerOption } from 'unified-map';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { MapUiService } from '../map-ui.service';

@Component({
  selector: 'app-base-layer-picker',
  templateUrl: './base-layer-picker.component.html',
  styleUrls: ['./base-layer-picker.component.scss']
})
export class BaseLayerPickerComponent implements OnInit, OnDestroy {
  @Input() selectedDataset: { '2d': LayerDataSet; '3d': LayerDataSet } = {
    '2d': 'MapStreets', '3d': 'MapStreets'
  };
  switchModeButtonText: '3D' | '2D' = '3D';
  currentLayerModel: BaseLayerViewModel = { dataset: 'MapStreets', icon: 'MapStreets', name: 'MapStreet晕眩地图' };
  iconPath = './assets/images/map/base-layer-picker';
  layerActivated = false;
  iconSize = 54;
  layerOptions: Array<BaseLayerViewModel> = [
    // { dataset: 'GoogleAerial', icon: 'GoogleAerial', name: 'GOOGLE影像' },
    { dataset: 'EsriAerial', icon: 'EsriAerial', name: 'ESRI影像' },
    { dataset: 'BingAerial', icon: 'BingAerial', name: 'Bing影像' },
    { dataset: 'TianAerial', icon: 'EsriAerial', name: '天地图影像' },
    { dataset: 'OSMStandard', icon: 'OSMStandard', name: 'Open Street Map', description: 'Open Street Map - 标准地图' },
    // { dataset: 'MapStreets', icon: 'MapStreets', name: 'MapStreet晕眩地图' },
    { dataset: 'OSMCycle', icon: 'OSMCycle', name: 'OSM Cycle', description: 'Open Street Map - 地形晕眩地图' }
  ];
  tileServiceUrl: string = (window as any).environment.tileServiceUrl;

  // tslint:disable-next-line:variable-name
  private _unsubscribe: Subject<void> = new Subject<void>();

  constructor(private unifiedMapService: UnifiedMapService, private mapService: MapUiService) { }

  ngOnInit(): void {
    this.unifiedMapService.switchComplete.pipe(
      takeUntil(this._unsubscribe)
    ).subscribe(mode => {
      if (mode) {
        this.switchModeButtonText = mode === '2d' ? '3D' : '2D';
      }
    });
  }

  ngOnDestroy(): void {
    this._unsubscribe.next();
    this._unsubscribe.complete();
  }

  switchMapMode(): void {
    this.unifiedMapService.switchMapMode();
  }

  setBaseLayer(layer: BaseLayerViewModel): void {
    const mapMode = this.unifiedMapService.mapMode;
    if (this.selectedDataset[mapMode] === layer.dataset) {
      return;
    }
    this.currentLayerModel = layer;
    this.selectedDataset[mapMode] = layer.dataset;
    const baseLayerOptions: ImageryTileLayerOption = {
      url: `${this.tileServiceUrl}imagery/${layer.dataset}/{z}/{x}/{y}`,
      serviceType: 'xyz',
      opacity: 1,
      minimumLevel: 0,
      maximumLevel: 20
    };
    this.unifiedMapService.mapInstance.setBaseLayer(baseLayerOptions);
  }

  initView() {
    this.mapService.initViewRange('view_guanyu');
  }
}
